<template>
  <div class="container preview-article form-design-container" v-loading="indexLoading" element-loading-text="表单生成中...">
    <div class="preview-header">
      <div class="audit-btn-box audit-btn-first">
        <span class="preview-text1">本地演示站点</span>
        <span class="line">|</span>
        <span class="preview-text2">{{ qsTypeName }}问卷</span>
      </div>
      <div class="header-tabs">
        <el-tabs v-model="headerActiveName" @tab-change="handleChange">
          <el-tab-pane label="编辑" :name="0"></el-tab-pane>
          <el-tab-pane label="外观" :name="1"></el-tab-pane>
          <el-tab-pane label="设置" :name="2"></el-tab-pane>
        </el-tabs>
      </div>
      <div class="audit-btn-box audit-btn-last">
        <button class="preview-btn" @click="publish">
          <i class="iconfont">&#xe6d8;</i>
          {{ publishBtnText }}
        </button>
        <button class="preview-btn" v-if="!curFormId" @click="staging">
          <i class="iconfont">&#xe6a7;</i>
          暂存
        </button>
        <button class="preview-btn" @click="dialogVisible = true">
          <i class="iconfont">&#xe6ee;</i>
          预览
        </button>
      </div>
    </div>
    <!-- 编辑 -->
    <div v-if="headerActiveName === 0" class="preview-content">
      <!-- 资源展开 -->
      <div class="publish-resource">
        <div class="resource-bar">
          <a
            href="javascript:;"
            class="resource-bar-item"
            :class="{ 'is-disabled': !item.canUse, 'is-choose': item.id === currentResource }"
            v-for="item in myResources"
            :key="item.id"
            @click="handleChooseResource(item)"
          >
            <div class="resource-bar-icon">
              <i class="iconfont" v-html="item.icon"></i>
            </div>
            <span>{{ item.name }}</span>
          </a>
        </div>
        <!-- 批量操作按钮 -->
        <div class="editor-rigth-btns-box">
          <div class="editor-rigth-btns">
            <el-tooltip class="box-item" effect="dark" content="批量操作" placement="right">
              <div class="circle tools" @click="dealAllQs">
                <i class="iconfont">&#xe68a;</i>
              </div>
            </el-tooltip>
          </div>
        </div>
        <!-- 批量操作弹框 -->
        <el-dialog v-model="showDealAllQs" title="批量操作" width="500px" align-center>
          <el-scrollbar class="deal-formComponents-box-scrollbar" max-height="500px">
            <div class="deal-formComponents-box">
              <div class="top-btn">
                <el-checkbox class="check-all" v-model="groupCheckedAll" @change="handleCheckAll" label="全选" />
                <el-button type="primary" :disabled="!canDeleteAll" link @click="deleteCmp()">批量删除</el-button>
              </div>
              <!-- filter=".unmover" -->
              <draggable
                class="dargCmpS"
                :group="{ name: 'formCmp' }"
                :animation="300"
                chosenClass="chosenClass"
                dragClass="dragClass"
                handle=".formComponents-move-btn"
                ghostClass=""
                :list="_formComponents"
                item-key="formItemId"
              >
                <template #item="{ element: cmp }">
                  <div class="formComponents-item">
                    <div class="formComponents-move-btn" :class="formInfo.onePageOneQs && cmp.type == 'pagenation' ? 'unmover' : ''">
                      <i class="iconfont">&#xe689;</i>
                    </div>
                    <el-checkbox :label="cmp.label || cmp.labelPlaceholder" v-model="cmp.checked">
                      <template #default>
                        <div class="pagenation" v-if="cmp.type == 'pagenation'">
                          <span>{{ `分页器(第${cmp.labelIndex}页)` }}</span>
                        </div>
                        <div class="no-pagenation" v-else>
                          <span>{{ cmp.labelIndex }} .</span>
                          <span :title="cmp.label || cmp.labelPlaceholder">{{ cmp.label || cmp.labelPlaceholder }}</span>
                        </div>
                      </template>
                    </el-checkbox>
                    <el-tooltip class="box-item" effect="dark" content="定位到当前问题位置" placement="left">
                      <div class="goto-qs" @click="gotoQsLocation(cmp)">
                        <i class="iconfont">&#xe900;</i>
                      </div>
                    </el-tooltip>
                    <el-tooltip class="box-item" effect="dark" content="删除题目" placement="right">
                      <div class="goto-qs" @click="deleteCmp(cmp)">
                        <i class="iconfont">&#xe74b;</i>
                      </div>
                    </el-tooltip>
                  </div>
                </template>
              </draggable>
            </div>
          </el-scrollbar>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="showDealAllQs = false">取消</el-button>
              <el-button type="primary" @click="dealAllQsSubmit">确定</el-button>
            </span>
          </template>
        </el-dialog>
        <Transition name="window">
          <div class="resource-window" v-show="currentResource !== 0">
            <!-- <a href="javascript:;" class="close-window-btn" @click="handleCloseWindow">
              <i class="iconfont">&#xe8e7;</i>
            </a> -->
            <div class="import-temps-content">
              <div class="header-search" v-if="currentResource === 1">
                <input type="text" clearable v-model="keywords" placeholder="请输入需要查找的关键词" />
                <a href="javascript:;" @click="filterByKeywords">
                  <i class="iconfont">&#xe643;</i>
                </a>
              </div>
              <div class="inner-temps-content">
                <el-scrollbar>
                  <div v-if="currentResource === 1">
                    <!-- 题型 -->
                    <ul class="questions-model" v-loading="curComponentListLoading">
                      <li class="formCmpType" v-for="(item, itemIndex) in _curComponentList" :key="itemIndex">
                        <div @click="item.show = !item.show" class="title">
                          <i class="iconfont" :class="item.show ? 'icon-rotate' : ''">&#xe601;</i>
                          {{ item.title }}
                        </div>
                        <el-collapse-transition>
                          <ul v-show="!item.show">
                            <draggable
                              animation="300"
                              :group="{
                                name: 'form',
                                pull: 'clone',
                                put: false
                              }"
                              chosenClass="chosenClass"
                              dragClass="dragClass"
                              ghostClass="ghostClass"
                              :sort="false"
                              :list="item.list"
                              item-key="name"
                            >
                              <template #item="{ element }">
                                <li class="formCmp" :class="element.type == 'pagenation' && formInfo.onePageOneQs ? 'pagenation-cmp-disabled' : ''" @click="formCmpClick(element)">
                                  <div class="label">
                                    <i class="iconfont" v-html="element.icon || '&#xe8b0;'"></i>
                                    <span :title="element.compName">{{ element.compName }}</span>
                                  </div>
                                </li>
                              </template>
                            </draggable>
                          </ul>
                        </el-collapse-transition>
                      </li>
                    </ul>
                  </div>
                  <!-- 题库 -->
                  <keep-alive>
                    <QsBank ref="QsBankRef" v-if="currentResource === 2" @formCmpClick="formCmpClick" @handleBatchInsertQuestions="handleBatchInsertQuestions" @handleOnePageOneQs="handleOnePageOneQs" />
                  </keep-alive>
                </el-scrollbar>
              </div>
            </div>
          </div>
        </Transition>
      </div>
      <!-- 中间操作区域 -->
      <div class="preview-father">
        <div v-if="formAppearanceInfo.backgroundImg" class="background-image" :style="{ backgroundImage: 'url(' + formAppearanceInfo.backgroundImg + ')' }"></div>
        <div v-else class="background-color" :style="{ backgroundColor: formAppearanceInfo.backgroundColor }"></div>
        <div class="preview-box">
          <el-scrollbar ref="scrollRef">
            <div class="center-box">
              <div class="page-logo" v-show="formAppearanceInfo.showLogo">
                <img :src="formAppearanceInfo.logoImg" alt="" />
              </div>
              <div class="page-header" v-if="formAppearanceInfo.headerImg">
                <img :src="formAppearanceInfo.headerImg" alt="" />
              </div>
              <formDesignLabel class="form-design-top-title" :formItem="formInfo" />
              <formDesignDescription class="form-design-top-description" :formItem="formInfo" />
              <formNotice v-if="curId == 4 && formInfo.formNotice.isOpen" :formInfo="formInfo" />
              <form-center ref="formCenterRef" @changeScroll="changeScroll"></form-center>
            </div>
          </el-scrollbar>
        </div>
      </div>
      <!-- 右侧配置项 -->
      <div
        :class="{
          'safe-scan': true,
          'right-box': true,
          'col-expand': scanDrawer
        }"
      >
        <div class="safe-scan-detail">
          <div class="col-btn" @click="toggleExpand">
            <i class="iconfont">&#xe771;</i>
          </div>
          <div v-if="curId == 4" class="exam-statistics-box">
            <div  class="exam-statistics">
              <span>试卷总分</span>
              <span>{{ totalScore }}分</span>
            </div>
            <div class="exam-statistics">
              <span>及格分数</span>
              <span>{{ formInfo.publishSetting.passingScore }}分</span>
            </div>
          </div>
          <form-config :totalScore="totalScore" />
        </div>
      </div>
    </div>
    <!-- 外观 -->
    <div v-if="headerActiveName === 1">
      <formAppearance />
    </div>
    <!-- 设置 -->
    <div v-if="headerActiveName === 2">
      <formPublishSetting />
    </div>
    <!-- 表单预览 -->
    <el-dialog v-model="dialogVisible" title="问卷预览" width="1000px" align-center class="preview-dialog">
      <FormEcho :formData="formInfo" height="65vh" :disabled="false" :showDevice="true" />
    </el-dialog>
    <!-- 关闭页面提示 -->
    <el-dialog v-model="closeWindow" title="提示" width="400px" align-center class="preview-dialog">
      <div class="close-window">暂无当前模块权限，页面将在{{ closeNum }}秒后关闭！</div>
    </el-dialog>
  </div>
</template>

<script setup>
import formCenter from '@/views/form/manage/design/formCenter.vue'
import formConfig from '@/views/form/manage/design/formCmpConfig.vue'
import { FormEcho } from '@ruifox-cms/components'
import QsBank from '@/views/form/manage/design/components/qsBank.vue'
import formAppearance from '@/views/form/manage/design/formAppearance/formAppearance.vue'
import formPublishSetting from '@/views/form/manage/design/formPublishSetting/formPublishSetting.vue'
import { ref, reactive, computed, watch, onMounted,watchEffect } from 'vue'
import draggable from 'vuedraggable'
import formDesignLabel from '@/views/form/manage/design/components/formDesignLabel.vue'
import formDesignDescription from '@/views/form/manage/design/components/formDesignDescription.vue'
import formNotice from '@/views/form/manage/design/components/formNotice.vue'
import { useStore } from 'vuex'
import { ElMessageBox, ElMessage } from 'element-plus'
import { formPublish, formEdit, getCurFormInfo, formStaging } from '@/api/formDesign'
import { useRouter, useRoute } from 'vue-router'
import { setLocSaveId, getLocSaveId, removeLocSaveId } from '@/utils/storage'
import { encrypt, decrypt } from '@ruifox-cms/utils'

const store = useStore()
const router = useRouter()
const route = useRoute()
const routerParams = computed(() => {
  return router.currentRoute.value.query
})
const qsTypeName = computed(() => {
  return decrypt(routerParams.value?.qsTypeName || '') || ''
})
const curId = computed(() => {
  return decrypt(routerParams.value.id)
})
const curStatus = computed(() => {
  return routerParams.value.status
})
// 左侧组件列表数据
const curComponentList = computed(() => {
  return store.state.formDesignInfo.curComponentList
})
const curComponentListLoading = ref(false)
const closeWindow = ref(false)
const closeNum = ref(3)
const handleGetCurComponentList = async () => {
  try {
    curComponentListLoading.value = true
    await store.dispatch('formDesignInfo/handleGetCurComponentList', curId.value)
    filterByKeywords() //初始化执行一次筛选
    curComponentListLoading.value = false
  } catch (error) {
    // closeWindow.value = true //测试
    // let timer = setInterval(() => {
    //   closeNum.value--
    //   if (closeNum.value == 0) {
    //     clearInterval(timer)
    //     timer = null
    //     window.close()
    //   }
    // }, 1000)
  }
}
handleGetCurComponentList()
//设置表单当前ID和发布类型
store.commit('formDesignInfo/SET_curId', curId.value)
// 获取所有组件列表
store.dispatch('formDesignInfo/handleGetComponentList', curId.value)
store.dispatch('formDesignInfo/handleGetPresupposeOption')
// 总表单的属性
const formInfo = computed(() => store.getters.formDesignInfo)
const formComponents = computed(() => {
  return formInfo.value.formItemList || []
})
const formAppearanceInfo = computed(() => store.getters.formDesignInfo.formAppearanceInfo)
const formCenterRef = ref(null)
// 组件点击新增
const formCmpClick = (cmp, index) => {
  
  formCenterRef.value.handelFormCmpClickAdd(cmp, index)
}
const handleBatchInsertQuestions = (ids) => {
  formCenterRef.value.handleBatchInsertQuestions(ids)
}
const handleOnePageOneQs = () => {
  formCenterRef.value.handleOnePageOneQs(true)
}
//题目定位
const scrollRef = ref(null)
const changeScroll = top => {
  let val
  if (top) {
    val = top
  } else {
    val = document.getElementsByClassName('center-box')[0].getBoundingClientRect().height
  }
  scrollRef.value.scrollTo({
    top: val,
    behavior: 'smooth'
  })
}
// 弹窗预览
const dialogVisible = ref(false)
// 表单校验是否通过
const isRightForm = () => {
  let formList = JSON.parse(JSON.stringify(formComponents.value.filter(item => item.type != 'pagenation')))
  let repeatFormArr = formList.filter(cmp => {
    let repeat = false
    let map = new Map()
    if (Array.isArray(cmp.default)) {
      //判断是否有重复选项
      cmp.default.forEach(option => {
        map.set(option.label, option.label)
        if (!option.label) {
          //判断是否填写选项
          cmp.emptyLabel = true
        }
      })
      let labels = Object.keys(Array.from(map))
      if (labels.length !== cmp.default.length) {
        cmp.repeat = true
        repeat = true
      }
    }
    return repeat
  })
  let emptyCmpLabelArr = formList.filter(cmp => {
    if (cmp.label.trim() == '') {
      cmp.emptyQsLabel = true
    } else {
      cmp.emptyQsLabel = false
    }
    return cmp.label.trim() == ''
  })
  // 表单标题校验
  if (emptyCmpLabelArr.length) {
    emptyCmpLabelArr.forEach(cmp => {
      if (cmp.emptyQsLabel) {
        ElMessage({
          showClose: true,
          message: `题目${cmp.labelIndex}未填写标题，请填写`,
          type: 'warning'
        })
      }
    })
    return false
  }
  // 表单标题校验
  if (!formInfo.value.label.trim()) {
    ElMessage({
      showClose: true,
      message: `问卷标题未填写，请填写`,
      type: 'warning'
    })
    return false
  }
  // 选项校验
  if (repeatFormArr.length) {
    repeatFormArr.forEach(cmp => {
      if (cmp.emptyLabel) {
        ElMessage({
          showClose: true,
          message: `题目${cmp.labelIndex}有未填写选项，请填写`,
          type: 'warning'
        })
      } else if (cmp.repeat) {
        ElMessage({
          showClose: true,
          message: `题目${cmp.labelIndex}选项重复，请修改`,
          type: 'warning'
        })
      }
    })
    return false
  }
  // 答案校验（筛选出有分数且不需要人工评分的题目，并检查其答案是否为空）
  let scoreCmp = formList.filter(cmp => cmp.referScore && !cmp.isManual)
  if (scoreCmp.length) {
    let result = true
    scoreCmp.forEach(cmp => {
      if (!cmp.referAnswer) {
        ElMessage({
          showClose: true,
          message: `检测到考试题目${cmp.labelIndex}未设置正确答案`,
          type: 'warning'
        })
        result = false
      }
    })
    return result
  }
  //发布设置校验（有文件上传题时必须开启登陆填写）
  let loginLimit = formInfo.value.publishSetting.useAuth
  if (!loginLimit) {
    let uploadCmp = formList.filter(item => item.type.includes('Upload'))
    if (uploadCmp.length > 0) {
      ElMessage({
        showClose: true,
        message: `检测到问卷含有文件上传题目，请开启【设置】-【填写需登录】`,
        type: 'warning'
      })
      return false
    } else {
      return true
    }
  }
  return true
}
// 发布/编辑保存
const publish = () => {
  // 表单校验是否通过
  if (!isRightForm()) return
  ElMessageBox.confirm(`<div><p style="font-size: 16px;margin-bottom: 15px;">是否确认${publishBtnText.value}？</p></div>`, `${publishBtnText.value}确认`, {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    await clearMyTimer()
    if (curId.value != 4 && formInfo.value?.formNotice) formInfo.value.formNotice = null
    let res
    if (!curFormId.value) {
      //发布表单
      res = await formPublish({ ...formInfo.value })
    } else if (curFormId.value && curStatus.value == 5) {
      // 如果是发布草稿
      res = await formPublish({ ...formInfo.value, draftId: curFormId.value })
    } else {
      //编辑表单
      res = await formEdit({ ...formInfo.value, formId: encrypt(curFormId.value) })
    }
    if (res.code == 20000) {
      if (window.opener.updateFormDesignList) window.opener.updateFormDesignList(`${publishBtnText.value}成功`)
      // router.push({ path: '/form/manage/statistics', query: { formId: encrypt(res.data.formId) } })
    window.close()
    }
  })
}
const headerActiveName = ref(0)
const handleChange = val => {
  headerActiveName.value = val
}
if (route.query && route.query.from === 'share') {
  headerActiveName.value = 2
}
let leftModuleWidth = ref(430 + 'px') //左侧模块宽度
let rigthModuleWidth = ref(370 + 'px') //右侧模块宽度
const setPreviewFather = (isShow, boxWith = 500) => {
  let previewFather = document.querySelector('.preview-father')
  let previewBox = document.querySelector('.preview-box')
  let fWidth = previewFather.offsetWidth
  let bWidth = previewBox.offsetWidth
  let cutWidth = isShow ? boxWith : -boxWith
  if (fWidth - cutWidth < bWidth) {
    previewBox.style['left'] = '0'
    previewBox.style['transform'] = 'translateX(0)'
  } else {
    previewBox.style['left'] = '50%'
    previewBox.style['transform'] = 'translateX(-50%)'
  }
}
const scanDrawer = ref(true)
const toggleExpand = () => {
  scanDrawer.value = !scanDrawer.value
  setPreviewFather(scanDrawer.value, parseInt(rigthModuleWidth.value))
}
/***
 * 左侧资源列表
 * ***/
const myResources = reactive([
  {
    id: 1,
    icon: '&#xe66c;',
    name: '题型',
    canUse: true
  },
  {
    id: 2,
    icon: '&#xe66c;',
    name: '题库',
    canUse: true
  }
])
const currentResource = ref(1)
const handleChooseResource = item => {
  if (!item.canUse) return
  if (item.id === currentResource.value) {
    currentResource.value = 0
  } else {
    currentResource.value = item.id
    switch (item.id) {
      case 1:
    }
  }
}
// 暂存
const staging = () => {
  // 表单校验是否通过
  if (!isRightForm()) return
  ElMessageBox.confirm(`<div><p style="font-size: 16px;margin-bottom: 15px;">是否确认暂存？暂存后保存至我的草稿</p></div>`, `暂存确认`, {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    await clearMyTimer()
    let res = await formStaging(formInfo.value)
    if (res.code == 20000) {
      window.opener.updateFormDesignList(`暂存成功`)
      router.push({ path: '/form/my/list' })
    }
  })
}
let toolsBtnsWidth = ref(45 + 'px') //工具按钮宽度
let toolsBtnsHeigth = ref(45 + 'px') //工具按钮高度
const showDealAllQs = ref(false)
const _formComponents = ref([])
// 批量操作
const dealAllQs = () => {
  showDealAllQs.value = true
  _formComponents.value = formInfo.value.onePageOneQs ? JSON.parse(JSON.stringify(formComponents.value)).filter(item => item.type != 'pagenation') : JSON.parse(JSON.stringify(formComponents.value))
  // _formComponents.value = formInfo.value.onePageOneQs ? formComponents.value.filter(item=>item.type!='pagenation') : formComponents.value
}
const handleCheckAll = val => {
  _formComponents.value.forEach(item => (item.checked = val))
}
const deleteCmp = cmp => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除？</p><span style="font-size: 14px;color: #FF5240;">清除后内容将无法恢复</span></div>', '删除确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    if (cmp)
      _formComponents.value.splice(cmp.cmpIndex - 1, 1) //单个删除
    else {
      _formComponents.value = _formComponents.value.filter(item => !item.checked)
      if (groupCheckedAll.value) dealAllQsSubmit()
    }
  })
}
// 批量操作确认
const dealAllQsSubmit = () => {
  formInfo.value.formItemList = _formComponents.value
  if (formInfo.value.onePageOneQs) formCenterRef.value.handleOnePageOneQs(true)
  showDealAllQs.value = false
}
// 定位到当前问题位置
const gotoQsLocation = cmp => {
  showDealAllQs.value = false
  formCenterRef.value.getClientRect(cmp.formItemId)
}
watch(
  // 监听表单组件变化 给表单添加索引
  () => _formComponents.value,
  () => {
    // 非分页组件添加索引
    _formComponents.value
      .filter(item => item.type != 'pagenation' && item.type != 'secondTitle')
      .forEach((item, index) => {
        item.labelIndex = index + 1
      })
    // 组件索引
    _formComponents.value
      .filter(item => item.type != 'secondTitle')
      .forEach((item, index) => {
        item.cmpIndex = index + 1
      })
    // 分页组件添加索引
    let pagenations = _formComponents.value.filter(item => item.type == 'pagenation')
    pagenations.forEach((item, index) => {
      item.labelIndex = index + 1
    })
    let pagenationIndexArr = []
    _formComponents.value.forEach((item, index) => {
      if (item.type === 'pagenation') {
        if (!pagenationIndexArr.includes(index)) pagenationIndexArr.push(index)
      }
    })
    //计算每个分页器包含的题目开始结束索引
    pagenationIndexArr.forEach((item, itemIndex) => {
      let startCmp, endCmp
      let curPageCmp = _formComponents.value[item] //当前分页器
      startCmp = item
      if (pagenationIndexArr[itemIndex + 1]) {
        endCmp = pagenationIndexArr[itemIndex + 1] - 1
      } else {
        endCmp = _formComponents.value.length - 1
      }
      if (endCmp - startCmp === 0) {
        //标记当前分页器是否没有题目
        curPageCmp.noQs = true
      } else {
        curPageCmp.noQs = false
      }
      curPageCmp.startCmp = startCmp
      curPageCmp.endCmp = endCmp
    })
  },
  {
    deep: true
  }
)
const groupCheckedAll = ref(false)
const canDeleteAll = ref(false)
watch(
  // 监听是否全选, 全部删除是否可点
  () => _formComponents.value,
  newV => {
    groupCheckedAll.value = newV.every(item => item.checked)
    canDeleteAll.value = newV.some(item => item.checked)
  },
  { deep: true }
)
watch(
  //更新表单
  () => formInfo.value,
  newV => {
    store.commit('formDesignInfo/SET_FORMINFO', newV)
  },
  { deep: true }
)

// 定时保存
const interval = 30 * 1000
let onlineSaveTimer = null
let locSaveId = getLocSaveId()
let curFormId = ref(routerParams.value.formId ? decrypt(routerParams.value.formId) : null)
let isCopy = routerParams.value.isCopy
let publishBtnText = computed(() => {
  return curFormId.value && curStatus.value != 5 ? '再次保存' : '发布'
})
const indexLoading = ref(false)
// 关闭定时保存，清空相关信息
const clearMyTimer = () => {
  return new Promise(resolve => {
    if (process.env.NODE_ENV === 'development') console.log('清除表单缓存')
    if (onlineSaveTimer) clearInterval(onlineSaveTimer)
    onlineSaveTimer = null
    removeLocSaveId()
    window.localStorage.removeItem('text_forminfo')
    resolve()
  })
}
// 定时执行保存接口
const handleIntervalSave = () => {
  onlineSaveTimer = setInterval(() => {
    if (!locSaveId) locSaveId = Date.now() + '_' + Math.ceil(Math.random() * 99999999)
    setLocSaveId(locSaveId)
    window.localStorage.setItem('text_forminfo', JSON.stringify(formInfo.value))
  }, interval)
}
// 定时保存初始化
const saveInit = async () => {
  let hisInfo = JSON.parse(window.localStorage.getItem('text_forminfo'))
  if (curFormId.value) {
    //编辑或者草稿
    indexLoading.value = true
    let res = await getCurFormInfo({ formId: curFormId.value })
    store.commit('formDesignInfo/SET_FORMINFO', res.data)
    indexLoading.value = false
    if (isCopy) curFormId.value = null
    handleIntervalSave()
  } else if (locSaveId) {
    if (curId.value != hisInfo.publishSetting.typeId) {
      clearMyTimer()
      // 缓存不同题型
      setTimeout(() => {
        handleIntervalSave()
      }, interval)
      return
    }
    ElMessageBox.confirm('<div><p style="font-size: 14px;">您上次有编辑未保存的内容是否恢复内容</p></div>', '提示', {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
      .then(() => {
        store.commit('formDesignInfo/SET_FORMINFO', hisInfo)
        handleIntervalSave()
      })
      .catch(() => {
        clearMyTimer()
        setTimeout(() => {
          handleIntervalSave()
        }, interval)
      })
  } else {
    setTimeout(() => {
      handleIntervalSave()
    }, interval)
  }
}
// 筛选组件
const QsBankRef = ref()
const keywords = ref('')
const _curComponentList = ref([])
const filterByKeywords = () => {
  if (currentResource.value == 1) {
    _curComponentList.value = []
    curComponentList.value.forEach(group => {
      let newList = group.list.filter(cmp => cmp.compName.includes(keywords.value))
      if (newList.length) _curComponentList.value.push({ ...group, list: newList })
    })
  } else if (currentResource.value == 2) {
    QsBankRef.value.bankFilterByKeywords(keywords.value)
  }
}
// 考试试卷总分计算
const totalScore = computed(() => {
  let total = 0
  formComponents.value.forEach(item => {
    total += item.referScore ? item.referScore : 0
  })
  return total
})
// 监听计算属性并更新表单
watchEffect(() => {
  const newFormInfo = JSON.parse(JSON.stringify(formInfo.value))
  newFormInfo.publishSetting.totalScore = totalScore.value
  store.commit('formDesignInfo/SET_FORMINFO', newFormInfo)
})
//考试及格分数
// const passingScore = ref(1); // 初始值
// const updatePassingScore = (newValue) => {
//   passingScore.value = newValue
// }
onMounted(() => {
  saveInit()
})
</script>
<style lang="scss" scoped>
.container {
  .preview-header {
    height: 64px;
    background-color: $mainColor;
    display: flex;
    padding: 0 20px;
    justify-content: space-between;
    align-items: center;
    .header-tabs {
      ::v-deep(.el-tabs__item) {
        color: $white;
      }
      ::v-deep(.el-tabs__item.is-active) {
        color: $white;
      }
      ::v-deep(.el-tabs__nav-wrap::after) {
        background: transparent;
      }
      ::v-deep(.el-tabs__active-bar) {
        background: $white;
      }
      ::v-deep(.el-tabs__header) {
        margin: 0;
      }
    }
    .audit-btn-box {
      min-width: 300px;
      display: flex;
      .preview-btn {
        height: 32px;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 0 15px;
        border: 1px solid $white;
        border-radius: 4px;
        background-color: inherit;
        color: $white;
        margin-right: 10px;
        cursor: pointer;
        transition: all 0.3s;
        .iconfont {
          margin-right: 3px;
        }
      }
      .preview-btn.preview-way-btn:hover {
        color: $mainColor;
        background-color: $white;
      }
      .preview-btn.preview-way-btn.active {
        color: $mainColor;
        background-color: $white;
      }
      .preview-btn:hover {
        background-color: rgba($white, 0.1);
      }
      .preview-text1 {
        font-style: 16px;
        color: $white;
      }
      .preview-text2 {
        font-style: 14px;
        color: $white;
      }
      .line {
        margin: 0 10px;
        color: $white;
      }
    }
    .audit-btn-last {
      display: flex;
      justify-content: flex-end;
    }
  }
  .preview-content {
    width: 100vw;
    box-sizing: border-box;
    overflow-x: auto;
    overflow-y: hidden;
    height: calc(100vh - 64px);
    background-color: $focusContent;
    display: flex;
    justify-content: space-between;
    .publish-resource {
      display: flex;
      z-index: 1;
      position: relative;
      .editor-rigth-btns-box {
        position: absolute;
        top: 20px;
        right: -54px;
        height: v-bind(toolsBtnsHeigth);
        overflow: hidden;
        transition: all 0.4s;
        // box-shadow: 0px 3px 5px rgba(0, 0, 0, 0.8);
        .editor-rigth-btns {
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          .tools {
            border-radius: 5px;
          }
          .circle {
            width: v-bind(toolsBtnsWidth);
            height: v-bind(toolsBtnsHeigth);
            border-bottom: 1px #fff solid;
            margin-left: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            cursor: pointer;
            font-size: 14px;
            background: $mainColor;
            color: #fff;
            box-sizing: border-box;
            overflow: hidden;
            .el-icon,
            i {
              font-size: 24px;
            }
            &:first-child {
              border-radius: 5px;
            }
            &:last-child {
              border-bottom-left-radius: 5px;
              border-bottom-right-radius: 5px;
            }
          }
        }
      }
      .resource-bar {
        width: 60px;
        box-sizing: border-box;
        border-right: 1px solid #dcdfe6;
        height: 100%;
        background-color: $white;
        padding: 30px 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        a.resource-bar-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin-bottom: 30px;
          color: #444;
          .resource-bar-icon {
            height: 40px;
            width: 40px;
            margin-bottom: 10px;
            background-color: #f0f2f7;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 10px;
            i {
              font-size: 20px;
              font-weight: bold;
            }
          }
          span {
            font-size: 12px;
          }
        }
        a.resource-bar-item.is-disabled {
          color: #aaaaaa;
          cursor: not-allowed;
        }
        a.resource-bar-item.is-choose {
          color: $mainColor;
          .resource-bar-icon {
            background-color: var(--el-color-primary-light-8);
          }
        }
      }
      .resource-window {
        width: 370px;
        height: 100%;
        box-shadow: 5px 0 10px rgba(0, 0, 0, 0.1);
        background-color: $white;
        overflow: hidden;
        position: relative;
        .close-window-btn {
          position: absolute;
          i {
            font-size: 20px;
          }
          right: 15px;
          top: 15px;
        }
        .import-temps-content {
          // padding-bottom: 40px;
          width: 100%;
          box-sizing: border-box;
          height: 100%;
          .header-search {
            height: 68px;
            box-sizing: border-box;
            margin: 0 20px 20px;
            border-bottom: 1px solid #dcdfe6;
            display: flex;
            align-items: center;
            input {
              border: none;
              outline: none;
              flex: 1;
            }
          }
          .header-class {
            display: flex;
            height: 52px;
            padding: 0 20px;
            justify-content: space-around;
            a {
              display: block;
              height: 32px;
              line-height: 32px;
              padding: 0 10px;
              border-radius: 32px;
            }
            a.active {
              color: #fff;
              background-color: $mainColor;
            }
          }
          .inner-temps-content {
            height: calc(100% - 100px);
            // 题型
            .questions-model {
              padding: 0 20px;
              box-sizing: border-box;
              .formCmpType {
                text-align: left;
                color: rgba(0, 0, 0, 0.85);
                .title {
                  padding: 10px 0;
                  margin-bottom: 10px;
                  color: #000;
                  font-weight: 600;
                  font-style: 16px;
                  cursor: pointer;
                  .iconfont {
                    margin-right: 5px;
                    font-weight: normal;
                    transition: all 0.3s;
                  }
                  .icon-rotate {
                    transform: rotate(-90deg);
                  }
                }
                > ul {
                  > div {
                    width: 100%;
                    display: flex;
                    flex-wrap: wrap;
                    box-sizing: border-box;
                    justify-content: space-between;
                    align-items: center;
                  }
                  .formCmp {
                    width: 160px;
                    height: 40px;
                    font-size: 14px;
                    color: #333;
                    text-align: center;
                    border: 1px solid #e5e5e5;
                    border-radius: 5px;
                    box-sizing: border-box;
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    margin-bottom: 10px;
                    .label {
                      width: 70%;
                      text-align: left;
                      overflow: hidden;
                      white-space: nowrap;
                      text-overflow: ellipsis;
                      .iconfont {
                        margin-left: 16px;
                        margin-right: 10px;
                      }
                    }
                    &:hover {
                      cursor: move;
                      color: $mainColor;
                      border: 1px solid $mainColor;
                      background: $checkColor;
                      .iconfont {
                        color: $mainColor;
                      }
                    }
                  }
                }
              }
            }

            .scroll-temps-content {
              padding: 0 20px;
              display: flex;
              flex-direction: column;
              .temps-item {
                width: 100%;
                margin-bottom: 20px;
                box-sizing: border-box;
                border-radius: 4px;
                border: 1px dashed rgba(0, 0, 0, 0.2);
                cursor: pointer;
                transition: all 0.2s;
                .temps-box {
                  width: 100%;
                  border-bottom: 1px dashed rgba(0, 0, 0, 0.2);
                }
                .temps-name {
                  line-height: 30px;
                  text-align: center;
                }
                &:hover {
                  border-color: $mainColor;
                  .temps-box {
                    border-color: $mainColor;
                  }
                }
              }
            }
          }
        }
      }
    }
    .left-box {
      box-sizing: border-box;
      width: 0;
      background: #fff;
      margin-right: 30px;
      position: relative;
      transition: all 0.8s;
      z-index: 9;
      .col-btn-left {
        position: absolute;
        height: 120px;
        width: 16px;
        right: -16px;
        top: 50%;
        transform: translateY(-50%);
        border-top-right-radius: 4px;
        border-bottom-right-radius: 4px;
        background-color: $mainColor;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        flex-direction: column;
        z-index: 1;
        span {
          font-size: 14px;
          writing-mode: tb-rl;
          display: block;
          margin-bottom: 5px;
          color: #fff;
        }
        i {
          color: #fff;
          font-size: 12px;
          transform: rotate(-90deg);
        }
      }
    }
    .left-box.col-expand-left {
      width: v-bind(leftModuleWidth);
      flex-shrink: 0;
      box-shadow: 5px 0 5px rgba(0, 0, 0, 0.1);
      .col-btn-left i {
        transform: rotate(90deg);
      }
    }
    .preview-father {
      box-sizing: border-box;
      position: relative;
      flex: 1;
      display: flex;
      justify-content: center;
      flex-shrink: 0;
      .background-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-size: cover;
        background-repeat: no-repeat;
        filter: blur(3px);
      }
      .background-color {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
      }
      .preview-box {
        width: 880px;
        height: 100%;
        position: absolute;
        top: 10px;
        left: 50%;
        transform: translateX(-50%);
        box-sizing: border-box;
        transition: all 0.8s;
        .center-box {
          background-color: #fff;
          min-height: calc(100vh - 84px);
          box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
          border-radius: 8px;
          overflow: hidden;
          box-sizing: border-box;
          padding-bottom: 40px;
          position: relative;
          transition: all 0.5s;
          // 标题
          .form-design-top-title {
            box-sizing: border-box;
            margin-top: 40px;
            padding: 0 80px;
            margin-bottom: 10px;
            ::v-deep(.form-design-label-index) {
              display: none;
            }
            ::v-deep(.el-textarea__inner) {
              padding: 12px 11px;
              padding-right: 58px;
              font-size: 24px;
              text-align: center;
            }
            ::v-deep(.el-input__count) {
              top: 22px;
              right: 2px;
            }
          }
          .form-design-top-description {
            padding-left: 80px;
            padding-right: 37px;
            box-sizing: border-box;
          }
          .page-logo {
            padding: 10px;
            height: 40px;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
            background: #fff;
            img {
              width: 100%;
              height: 100%;
              object-fit: contain;
              object-position: left;
            }
          }
          .page-header {
            height: 200px;
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }
        }
      }
    }
    .safe-scan {
      width: 0;
      background: #fff;
      z-index: 0;
      // margin-left: 22px;
      transition: width 0.8s;
      position: relative;
      box-sizing: border-box;
      .safe-scan-detail {
        overflow: hidden;
      }
      .col-btn {
        position: absolute;
        height: 120px;
        width: 16px;
        left: -16px;
        top: 50%;
        transform: translateY(-50%);
        border-top-left-radius: 4px;
        border-bottom-left-radius: 4px;
        background-color: $mainColor;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        flex-direction: column;
        span {
          font-size: 14px;
          writing-mode: tb-rl;
          display: block;
          margin-bottom: 5px;
          color: #fff;
        }
        i {
          color: #fff;
          font-size: 12px;
          transform: rotate(90deg);
        }
      }
      .exam-statistics-box {
        position: absolute;
        top: 20px;
        left: 0;
        transform: translateX(-110%);
      }
      .exam-statistics {
        margin-bottom: 10px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        padding: 10px;
        border-radius: 5px;
        background: $mainColor;
        color: #fff;
        font-weight: bold;
        font-size: 16px;
      }
    }
    .safe-scan.col-expand {
      width: v-bind(rigthModuleWidth);
      flex-shrink: 0;
      box-shadow: -5px 0 5px rgba(0, 0, 0, 0.1);
      .col-btn i {
        transform: rotate(-90deg);
      }
    }
  }
}
ul,
li {
  list-style: none;
  padding: 0;
  margin: 0;
}
/*定义要拖拽元素的样式*/
.ghostClass {
  border: 3px dashed $mainColor;
  height: 120px;
}
/* 选中的样式 */
.chosenClass {
  opacity: 0.7;
}
/* 拖动的样式 */
.dragClass {
  background-color: #fff !important;
  opacity: 0.7 !important;
  border: 2px dashed $mainColor !important;
  box-shadow: none !important;
  outline: none !important;
  background-image: none !important;
}
.center-box {
  flex: 1;
  margin: 0 10px;
  border: 1px #dfd6d6 solid;
  .operating-area {
    padding-left: 20px;
    i {
      font-size: 16px;
      color: rgb(131, 131, 131);
      font-weight: 700;
      &:hover {
        color: #4395ff;
      }
    }
  }
  .el-input {
    margin-bottom: 20px;
  }
}
.safe-scan-detail {
  ::v-deep .el-tabs__header {
    padding: 0 20px;
    margin-bottom: 0;
  }
  ::v-deep .el-tabs__content {
    padding: 0 20px;
  }
  ::v-deep .el-tabs__item {
    line-height: 56px;
    height: 56px;
    font-size: 16px;
  }
  ::v-deep .el-form-item__label {
    text-align: center;
  }
}
.window-enter-to,
.window-leave-from {
  max-width: 370px;
}
.window-enter-active,
.window-leave-active {
  transition: all 0.8s;
}
.window-enter-from,
.window-leave-to {
  max-width: 0;
}
// 禁用分组组件
.pagenation-cmp-disabled {
  .label {
    user-select: none !important;
    // background: #4395ff;
    color: #999 !important;
  }
}
.deal-formComponents-box-scrollbar {
  width: 100%;
}
// 批量操作弹框
.deal-formComponents-box {
  width: 100%;
  padding: 0 40px;
  box-sizing: border-box;
  .top-btn {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    .check-all {
      margin-left: 34px;
    }
  }
  .formComponents-item {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .formComponents-move-btn {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 10px;
      cursor: pointer;
      i {
        font-size: 24px;
        color: $mainColor;
      }
    }
    .unmover {
      i {
        user-select: none;
        color: #666;
      }
    }
    .goto-qs {
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      margin-left: 10px;
      i {
        color: $mainColor;
      }
    }
    .el-checkbox {
      width: 100%;
      ::v-deep(.el-checkbox__label) {
        width: calc(100% - 100px);
        @include textEllipsis(18px, 1);
      }
    }
  }
}
.close-window {
  font-size: 16px;
  .num {
    color: $mainColor;
    font-size: 20px;
  }
}

::v-deep(.preview-dialog .el-dialog__body) {
  padding: 0;
}
</style>
